package top.lushi78778.iot.mqtt.web.api.v1;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.onsmqtt20200420.models.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.lushi78778.iot.mqtt.configurer.MqttConfigurer;
import top.lushi78778.iot.mqtt.core.MqttClient;
import top.lushi78778.iot.mqtt.core.Result;
import top.lushi78778.iot.mqtt.core.ResultGenerator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName GroupId
 * @Description Group管理接口
 * @Author lushi
 * @Date 2021/7/18 17:31
 */
@RestController
@RequestMapping("/api/group")
public class GroupId {

    /**
     * 调用CreateGroupId创建Group ID
     *
     * @param GroupId 您需创建的 Group ID 以 "GID_" 或者 "GID-" 开头，只能包含字母、数字、连字符（-）和下划线（_），长度限制在 7~64 字符之间
     * @return RequestId 公共参数
     * @throws Exception 异常
     */
    @ApiOperation(value = "创建 Group ID")
    @RequestMapping(value = "/create",method = {RequestMethod.POST})
    public Result<Object> CreateGroupId(@ApiParam(value = "以 \"GID_\" 或者 \"GID-\" 开头，只能包含字母、数字、连字符（-）和下划线（_），长度限制在 7~64 字符之间",required = true) @RequestParam String GroupId) throws Exception {
        Pattern pattern = Pattern.compile("^GID[\\-_][A-Za-z0-9_\\-]{3,60}$");
        Matcher matcher = pattern.matcher(GroupId);
        if (matcher.find()) {
            MqttConfigurer mqttConfigurer = new MqttConfigurer();
            com.aliyun.onsmqtt20200420.Client client = MqttClient.createClient(mqttConfigurer.getAccesskey(), mqttConfigurer.getSecretkey(), mqttConfigurer.getEndpoint());
            CreateGroupIdRequest createGroupIdRequest = new CreateGroupIdRequest()
                    .setGroupId(GroupId)
                    .setInstanceId(mqttConfigurer.getInstanceid());
            try {
                CreateGroupIdResponse response = client.createGroupId(createGroupIdRequest);
                JSONObject json = new JSONObject(response.toMap());
                String data = String.valueOf(json.getJSONObject("body"));
                return ResultGenerator.genSuccessResult(data);
            } catch (Exception exception) {
                return ResultGenerator.genFailResult(exception.getMessage());
            }
        } else {
            return ResultGenerator.genFailResult("以 \"GID_\" 或者 \"GID-\" 开头，只能包含字母、数字、连字符（-）和下划线（_），长度限制在 7~64 字符之间");
        }
    }

    /**
     * 调用DeleteGroupId删除Group ID
     *
     * @param GroupId 您需要删除的Group ID
     * @return RequestId 公共参数
     * @throws Exception 异常
     */
    @ApiOperation(value = "删除 Group ID")
    @RequestMapping(value = "/delete",method = {RequestMethod.POST})
    public Result<Object> DeleteGroupId(@ApiParam(value = "以 \"GID_\" 或者 \"GID-\" 开头，只能包含字母、数字、连字符（-）和下划线（_），长度限制在 7~64 字符之间",required = true)@RequestParam String GroupId) throws Exception {
        Pattern pattern = Pattern.compile("^GID[\\-_][A-Za-z0-9_\\-]{3,60}$");
        Matcher matcher = pattern.matcher(GroupId);
        if (matcher.find()) {
            MqttConfigurer mqttConfigurer = new MqttConfigurer();
            com.aliyun.onsmqtt20200420.Client client = MqttClient.createClient(mqttConfigurer.getAccesskey(), mqttConfigurer.getSecretkey(), mqttConfigurer.getEndpoint());
            DeleteGroupIdRequest deleteGroupIdRequest = new DeleteGroupIdRequest()
                    .setGroupId(GroupId)
                    .setInstanceId(mqttConfigurer.getInstanceid());
            try {
                DeleteGroupIdResponse response = client.deleteGroupId(deleteGroupIdRequest);
                JSONObject json = new JSONObject(response.toMap());
                String data = String.valueOf(json.getJSONObject("body"));
                return ResultGenerator.genSuccessResult(data);
            } catch (Exception exception) {
                return ResultGenerator.genFailResult(exception.getMessage());
            }
        } else {
            return ResultGenerator.genFailResult("以 \"GID_\" 或者 \"GID-\" 开头，只能包含字母、数字、连字符（-）和下划线（_），长度限制在 7~64 字符之间");
        }
    }

    /**
     * 调用ListGroupId查看某实例下的所有Group ID
     *
     * @return Data 查询的Group ID的详细信息 RequestId 公共参数
     * CreateTime 该Group ID的创建时间
     * GroupId 查询到的属于该实例的Group ID
     * IndependentNaming 该实例是否有独立命名空间 true：有独立命名空间，该实例下的资源需保证命名唯一，跨实例可重名。 false：无独立命名空间，该实例下的资源需保证全局命名唯一，跨实例不可重名。
     * InstanceId 查询的Group ID所属实例的ID
     * UpdateTime 该Group ID的最近一次更新时间
     * @throws Exception 异常
     */
    @ApiOperation(value = "查看某实例下的所有 Group ID")
    @RequestMapping(value = "/list",method = {RequestMethod.POST})
    public Result<Object> ListGroupId() throws Exception {
        MqttConfigurer mqttConfigurer = new MqttConfigurer();
        com.aliyun.onsmqtt20200420.Client client = MqttClient.createClient(mqttConfigurer.getAccesskey(), mqttConfigurer.getSecretkey(), mqttConfigurer.getEndpoint());
        ListGroupIdRequest listGroupIdRequest = new ListGroupIdRequest()
                .setInstanceId(mqttConfigurer.getInstanceid());
        try {
            ListGroupIdResponse response = client.listGroupId(listGroupIdRequest);
            JSONObject json = new JSONObject(response.toMap());
            String data = String.valueOf(json.getJSONObject("body"));
            return ResultGenerator.genSuccessResult(data);
        } catch (Exception exception) {
            return ResultGenerator.genFailResult(exception.getMessage());
        }

    }
}
